﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace SQLQuery
{
    public partial class frmMain : Form
    {
        Int32 W_Id = 0;

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.Visible = true;
            CreateObjects();
        }

        /// <summary>
        /// Método para criar os objetos em tempo de execusão ao iniciar o sistema e ao clicar no botão "new"
        /// </summary>
        private void CreateObjects()
        {
            frmDatabaseConnection fDBConn = new frmDatabaseConnection();
            

            W_Id++;

            TabPage tPage = new TabPage();
            tPage.Text = "New Query " + W_Id.ToString();
            
            SQLEditor.Editor sqlEditor = new SQLEditor.Editor();
            sqlEditor.Name = "sqlEditor" + W_Id.ToString();
            sqlEditor.Dock = DockStyle.Fill;

            tPage.Controls.Add(sqlEditor);

            this.tMain.TabPages.Add(tPage);
            this.tMain.SelectedIndex = this.tMain.TabCount - 1;

            fDBConn.ShowDialog();
            sqlEditor.SetConnection(fDBConn.GetConnection());
        }

        /// <summary>
        /// Pesquisa e retorna um objeto, o qual o mesmo foi criado em tempo de execusão.
        /// </summary>
        /// <param name="tPage">Aba que deseja ser pesquisado</param>
        /// <param name="ObjectName">Nome do objeto</param>
        /// <returns>Objeto solicitado</returns>
        private object GetObjectsForm(TabPage tPage, String ObjectName)
        {
            Object obj = new object();

            Control[] ctrl = this.tMain.SelectedTab.Controls.Find(ObjectName, true);
            if (ctrl.Count() > 0)
            {
                obj = ctrl[0];
            }

            return obj;
        }

        /// <summary>
        /// Abre arquivo salvo no formato .sql
        /// </summary>
        private void Open()
        {
            try
            {
                if (this.ofdFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    FileInfo f = new FileInfo(ofdFile.FileName);
                    if (f.Exists)
                    {
                        StreamReader sr = new StreamReader(ofdFile.FileName);

                        CreateObjects();
                        ((SQLEditor.Editor)GetObjectsForm(this.tMain.SelectedTab, "sqlEditor" + W_Id.ToString())).OpenFile(sr.ReadToEnd());
                        this.tMain.SelectedTab.Text = ofdFile.FileName.Substring(0, 10) + "..." + ofdFile.FileName.Substring(ofdFile.FileName.Length - 20, 20);
                        this.tMain.SelectedTab.Name = ofdFile.FileName;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Salva arquivo no formato .sql
        /// </summary>
        private void Save()
        {
            try
            {
                int id = this.tMain.SelectedIndex + 1;

                if (!String.IsNullOrEmpty(((SQLEditor.Editor)GetObjectsForm(this.tMain.SelectedTab, "sqlEditor" + id.ToString())).SaveFile()))
                {
                    StreamWriter sw;
                    if (!String.IsNullOrEmpty(this.tMain.SelectedTab.Name))
                    {
                        sw = new StreamWriter(sfdFile.FileName);
                    }
                    else if (sfdFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        sw = new StreamWriter(sfdFile.FileName);
                        sw.Write(((SQLEditor.Editor)GetObjectsForm(this.tMain.SelectedTab, "sqlEditor" + id.ToString())).SaveFile());
                        sw.Close();

                        this.tMain.SelectedTab.Text = sfdFile.FileName.Substring(0, 10) + "..." + sfdFile.FileName.Substring(sfdFile.FileName.Length - 20, 20); ;
                        this.tMain.SelectedTab.Name = sfdFile.FileName;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void cmdOPen_Click(object sender, EventArgs e)
        {
            this.Open();            
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            this.Save();
        }

        private void cmdNew_Click(object sender, EventArgs e)
        {
            CreateObjects();
        }
    }
}
